package com.huwei.modules.base.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.huwei.modules.base.constant.JsonResultConstant;
import com.huwei.modules.base.shiro.JwtShiroToken;

@RestController
public class LoginController {

	@RequestMapping(value="/toLogin" ,produces= {MediaType.APPLICATION_JSON_UTF8_VALUE})
	public String toLogin() {
		return "this is login page";
	}
	
	@RequestMapping(value="/login")
	public void login(String token,HttpServletResponse response) throws IOException {
		System.out.println("--------------------------------- login ---------------------------");
		JwtShiroToken jwtToken = new JwtShiroToken(token);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(jwtToken);
		}catch (Exception e) {
			e.printStackTrace();
			//登录失败，密码错误
			response.sendRedirect("toLogin");
			return;
		}
		response.sendRedirect("home");
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/home" ,produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
	public JsonResultConstant home() {
		Subject subject = SecurityUtils.getSubject();
		Map<String,String> userInfo =  (Map<String, String>) subject.getPrincipal();
		System.out.println("---> 登录用户信息：" + userInfo);
		return JsonResultConstant.success(null, userInfo);
	}
}
